# -*- coding: utf-8 -*-
from gm.api import *


def init(context):
    context.symbol_1 = "SHSE.601939"
    context.symbol_2 = "SHSE.601288"
    context.weight = 0.481477
    context.bias = 0.481829
    context.mean = -0.000203539120501
    context.std = 0.0754807889752
    schedule(schedule_func=algo, date_rule='1d', time_rule='09:31:00')

    context.flagX = False
    context.flagY = False


def algo(context):
    last_day = get_previous_trading_date("SHSE", context.now)
    ccb = history(context.symbol_1, frequency='1d', start_time=last_day, end_time=last_day, fields="close",
                  fill_missing="last", adjust=ADJUST_PREV, df=True)
    abchina = history(context.symbol_2, frequency="1d", start_time=last_day, end_time=last_day, fields="close",
                      fill_missing="last", adjust=ADJUST_PREV, df=True)

    ccb = (ccb['close'].values)
    abchina = (abchina['close'].values)

    d_value = abchina - (ccb * context.weight + context.bias)

    if (context.flagX and d_value < context.mean + context.std) or (
            context.flagY and d_value > context.mean - context.std):
        order_close_all()
        context.flagX = False
        context.flagY = False
    if d_value < context.mean + 3 * context.std:
        order_target_percent(symbol=context.symbol_2, percent=1, position_side=PositionSide_Long,
                             order_type=OrderType_Market)
        context.flagY = True

    if d_value > context.mean + 3 * context.std:
        order_target_percent(symbol=context.symbol_1, percent=1, position_side=PositionSide_Long,
                             order_type=OrderType_Market)
        context.flagX = True


def on_backtest_finished(context, indicatior):
    print(indicatior)


if __name__ == '__main__':
    run(strategy_id='a5299b24-8b44-11e9-a4d4-b499baf0193a',
        filename='配对交易策略.py',
        mode=MODE_BACKTEST,
        token='90be3f863b23ab3c1ef68d1f9b8dc06e4bebb30d',
        backtest_start_time='2016-01-30 09:00:00',
        backtest_end_time='2016-12-30 15:00:00',
        backtest_initial_cash=100000,
        backtest_adjust=ADJUST_PREV,
        backtest_slippage_ratio=0.01,
        backtest_commission_ratio=0.0005,
        )
